from django.http import HttpResponse


def get_session(request,key):
    try:
        value = request.session[key]
        return value
    except KeyError:
        # 如果没有找到 key，则返回 None 或其他默认值
        return None
"""用户登录后鉴权中间件"""
class AuthMiddleware:
    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):
        print("============访问了中间件 author middleware===========")

        #排除url
        if request.path_info in ["/blog/to_login/","/blog/login/"]:
            response = self.get_response(request)
            return response
        #通过session检查是否有合法的权限
        user_id=get_session(request,"user_id")
        if user_id!= '999999':
            return HttpResponse("<script>alert('用户会话信息已失效，请先登录！');window.location.href='/blog/to_login/';</script>")
        else:
            print("用户已登录，user_id:",user_id)
            response = self.get_response(request)
            return response


